package chaoyue.study.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * 配置自定义的熔断异常处理
 * 替换针对没有配置Fallback的方法的默认处理逻辑
 */
@Component
public class MyBlockedExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setStatus(500);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        if(e instanceof FlowException){
            out.print("{\"error\":\"限流\"}");
        }else if(e instanceof DegradeException){
            out.print("{\"error\":\"熔断\"}");
        }
        out.flush();
        out.close();
    }
}
